<template>
  <div class="topic-list-page">
    <div style="margin-bottom: 16px; display: flex; align-items: center;">
      <el-button
        type="primary"
        size="small"
        @click="sortByPosts"
        :icon="isSorted ? 'el-icon-sort-down' : 'el-icon-sort-up'"
      >
        按动态数量排序
      </el-button>
      <span v-if="isSorted" style="margin-left: 10px; color: #409EFF;">已排序</span>
    </div>
    <el-row :gutter="20">
      <el-col
        v-for="topic in topicList.filter(t => t.status !== 0)"
        :key="topic.topicId"
        :span="12"
        class="topic-col"
      >
        <el-card shadow="hover" class="topic-card">
          <div class="topic-header">
            <span class="topic-title">{{ topic.title }}</span>
          </div>
          <div class="topic-desc">{{ topic.description }}</div>
          <div class="topic-time">创建时间：{{ formatTime(topic.createdAt) }}</div>
          <el-divider />
          <div class="topic-posts-title">动态内容：</div>
          <div v-if="topic.posts && topic.posts.length" class="topic-posts-list">
            <div v-for="post in topic.posts" :key="post.postId" class="topic-post-item">
              <div class="post-content">{{ post.content }}</div>
              <div class="post-media">
                <template v-if="post.mediaUrl">
                  <video
                    v-if="/\.(mp4|webm|ogg)$/i.test(post.mediaUrl)"
                    :src="post.mediaUrl"
                    controls
                    style="width: 80px; height: 80px; object-fit: cover; margin-right: 8px;"
                  ></video>
                  <img
                    v-else-if="/\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(post.mediaUrl)"
                    :src="post.mediaUrl"
                    style="width: 80px; height: 80px; object-fit: cover; border-radius: 4px; margin-right: 8px;"
                  />
                  <span v-else>未知格式</span>
                </template>
              </div>
              <div class="post-time">{{ formatTime(post.createdAt) }}</div>
            </div>
          </div>
          <div v-else class="no-posts">暂无动态</div>
        </el-card>
      </el-col>
    </el-row>
    <div v-if="topicList.some(t => t.status === 0)" class="deleted-topics">
      <h4>已删除话题（可恢复）</h4>
      <el-tag
        v-for="topic in topicList.filter(t => t.status === 0)"
        :key="topic.topicId"
        type="info"
        style="margin-right: 8px; margin-bottom: 8px;"
      >
        {{ topic.title }}
        <el-button
          type="success"
          size="mini"
          @click="restoreTopic(topic)"
          style="margin-left: 8px;"
        >恢复</el-button>
      </el-tag>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const topicList = ref([])
const originalList = ref([]) // 保存原始顺序
const isSorted = ref(false)

const formatTime = (time) => {
  if (!time) return '-'
  const d = new Date(time)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}

// 删除话题，调用后端接口
const deleteTopic = (topic) => {
  ElMessageBox.confirm(
    `确定要删除话题「${topic.title}」吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await http({
        url: http.adornUrl(`/social/topic/${topic.topicId}`),
        method: 'delete'
      })
      // 前端移除
      topicList.value = topicList.value.filter(t => t.topicId !== topic.topicId)
      originalList.value = originalList.value.filter(t => t.topicId !== topic.topicId)
      ElMessage.success('删除成功')
    } catch (e) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

const restoreTopic = (topic) => {
  // 如果有恢复接口可补充，否则可移除此功能
  ElMessage.info('如需恢复请联系管理员')
}

// 排序方法
const sortByPosts = () => {
  if (!isSorted.value) {
    // 先保存原始顺序
    originalList.value = topicList.value.slice()
    // 排序
    topicList.value = [...topicList.value].sort((a, b) => {
      const aCount = Array.isArray(a.posts) ? a.posts.length : 0
      const bCount = Array.isArray(b.posts) ? b.posts.length : 0
      return bCount - aCount
    })
    isSorted.value = true
  } else {
    // 恢复原始顺序
    topicList.value = originalList.value.slice()
    isSorted.value = false
  }
}

onMounted(async () => {
  try {
    const { data } = await http({
      url: http.adornUrl('/social/topic/page'),
      method: 'get',
      params: { current: 1, size: 100 }
    })
    topicList.value = data.records.map(item => ({
      ...item,
      status: item.status !== undefined ? item.status : 1
    }))
    originalList.value = topicList.value.slice()
  } catch (e) {
    ElMessage.error('话题列表加载失败')
  }
})
</script>

<style scoped>
.topic-list-page {
  padding: 32px 16px;
  background: #f5f7fa;
  min-height: 100vh;
}
.topic-col {
  margin-bottom: 24px;
}
.topic-card {
  min-height: 220px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.topic-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.topic-title {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}
.topic-desc {
  color: #666;
  margin: 12px 0 8px 0;
  min-height: 40px;
}
.topic-time {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}
.topic-posts-title {
  font-size: 15px;
  font-weight: bold;
  margin: 12px 0 4px 0;
  color: #333;
}
.topic-posts-list {
  margin-bottom: 8px;
}
.topic-post-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  background: #f8fafd;
  border-radius: 4px;
  padding: 6px 8px;
}
.post-content {
  flex: 1;
  color: #444;
  font-size: 14px;
}
.post-media {
  margin-left: 8px;
}
.post-time {
  font-size: 12px;
  color: #aaa;
  margin-left: 12px;
  min-width: 110px;
  text-align: right;
}
.no-posts {
  color: #bbb;
  text-align: center;
  padding: 8px 0;
}
.deleted-topics {
  margin-top: 24px;
  padding: 16px;
  background: #fff;
  border-radius: 4px;
}
</style>
